import axios from 'axios'
import {t, message, bs} from "@/service/index.js"


const service = axios.create({
    baseURL: import.meta.env.ENV_BASE_URL,
    timeout: import.meta.env.ENV_TIMEOUT,
})

// 上传方法 data={file: ,path: }
service.upload = function(url, data, time = import.meta.env.ENV_TIMEOUT) {
    let fd = new FormData();
    Object.keys(data).forEach(key => {
        if(key === 'files'){
            let files = data[key]
            for (let i = 0; i < files.length; i++) {
                fd.append('file', files[i])
            }
            return
        }
        fd.append(key, data[key])
    })
    return service.request({
        url: url,
        data: fd,
        method: 'post',
        timeout: time,
        headers: {'upload': true},
    })
}


// 添加请求拦截器
service.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    let token = bs().token
    config.headers["token"] = token ? token : null
    config.headers["Accept-Language"] = bs().localState.name
    if(config.headers["upload"]){
        config.headers["Content-Type"] = "multipart/form-data";
        return config;
    }
    config.data = {
        data: config.data
    }
    return config;
}, function (error) {
    // 对请求错误做些什么
    message.error(t(`axios.${error.response.status}`))
    return Promise.reject({
        msg: error.message,
        code: error.response.status,
        data: null
    });
});

// 添加响应拦截器
service.interceptors.response.use(function (response) {
    const data = response.data
    // 未登录
    if (data.code === 401) {
        message.error(data.msg)
        bs().token = null
        location.reload()
        return Promise.reject(data);
    }
    // 请求错误
    if (data.code !== 200) {
        message.warning(data.msg)
        return Promise.reject(data);
    }
    return data;
}, function (error) {
    message.error(t(`axios.${error.response.status}`))
    return Promise.reject({
        msg: error.message,
        code: error.response.status,
        data: null
    });
});


export default service